package com.ruijie.acl.web.validator;

import java.util.Map;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.apache.commons.lang.StringUtils;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.faces.Validator;

import com.ruijie.acl.utils.AclUtil;
import com.ruijie.emp.utils.NetUtils;
import com.ruijie.foundation.international.MessageSupport;
/**
 * <p>
 * Title: 变量值的多重验证器，会根据变量类型而采用相应的验证方法
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * 	变量值的合法性验证
 * </p>
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time: 2009-07-14
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 * 
 * @author ASAI
 */
@Name("variableValueMultiValidator")
@Validator
public class VariableValueMultiValidator  extends MessageSupport implements
javax.faces.validator.Validator{
	
	@In private Map<String, String> messages;
	
	/**
	 * 匹配数值的正则表达式
	 */
	private static Pattern PATTERN=Pattern.compile("[0-9]+");
	
	
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object obj) throws ValidatorException {
		String value=obj.toString().trim();
		Object typeObj=component.getAttributes().get("type");
		String type=null;
		if(typeObj==null){
			//类型信息未传入，输出：请重新选择类型
			throw new ValidatorException(new FacesMessage(
					getI18NMessage("acl_validator_template_var_type_reSelect")));
		}else{
			type=typeObj.toString().trim();
		}

		if(component.getAttributes().get("required").toString().equals("true")){
			if(!StringUtils.isNotEmpty(value.replaceAll("　",   " ").trim())){
				throw new ValidatorException(new FacesMessage(messages.get("javax.faces.component.UIInput.REQUIRED")));
			}
		}
		/*
		 * type 取值为：txt, num, ip, mask,mac;
		 */
		if("num".equals(type)){
			if(!PATTERN.matcher(value).matches()){
				throw new ValidatorException(new FacesMessage(
						getI18NMessage("acl_validator_template_var_value_no_num")));
			}
		}else if("ip".equals(type)){
			if(!AclUtil.ipV4Validator(value)){
				throw new ValidatorException(new FacesMessage(getI18NMessage("emp_common_validation_ipValidateFailed")));
			}
		}else if("mask".equals(type)){
			if(!AclUtil.maskValidator(value)){
				throw new ValidatorException(new FacesMessage(getI18NMessage("emp_device_validation_maskValidateFailed")));
			}
		}else if("mac".equals(type)){
			if(!NetUtils.isMACValidate(value)){
				throw new ValidatorException(new FacesMessage(getI18NMessage("emp_device_validation_macValidateFailed")));
			}
		}
	}

}
